package com.dw.gui.panel.diagnosis;

import com.dw.dao.other.AppointmentDao;
import com.dw.dao.record.MedicalRecordDao;
import com.dw.dao.user.PatientDao;
import com.dw.model.other.Appointment;
import com.dw.model.user.Doctor;
import com.dw.model.record.MedicalRecord;
import com.dw.util.UIUtil;
import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.sql.Date;
import java.sql.SQLException;
import java.time.LocalDate;

public class WriteRecordPanel extends JPanel {

    private final AppointmentDao appointmentDao = new AppointmentDao();
    private final PatientDao patientDao = new PatientDao();

    private final JTextField taPatientName = UIUtil.createTextField();
    private final JTextField taChiefComplaint = UIUtil.createTextField();

    private final JTextArea taHistory = UIUtil.createTextArea(3, 30);
    private final JTextArea taDiagnosis = UIUtil.createTextArea(3, 30);

    private final JTextField tfAppointmentId = UIUtil.createTextField();

    private Appointment appointment;
    private Doctor doctor;

    public WriteRecordPanel(Doctor doctor) {
        this.doctor = doctor;

        initUI();
    }

    private void initUI() {
        setLayout(new BorderLayout(10, 10));
        setBackground(Color.WHITE);

        // 创建面板标题
        JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        titlePanel.setBackground(Color.WHITE);
        titlePanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        JLabel titleLabel = UIUtil.createTitleLabel("病历书写");
        titlePanel.add(titleLabel);

        // 创建信息面板
        JPanel infoPanel = new JPanel(new GridBagLayout());
        infoPanel.setBackground(Color.WHITE);
        infoPanel.setBorder(BorderFactory.createTitledBorder("基本信息"));

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;

        gbc.gridx = 0;
        gbc.gridy = 0;
        infoPanel.add(UIUtil.createLabel("会诊ID："), gbc);
        gbc.gridx = 1;
        tfAppointmentId.addActionListener(e -> loadAppointment()); // 回车触发
        tfAppointmentId.addFocusListener(new FocusAdapter() {
            @Override
            public void focusLost(FocusEvent e) {
                loadAppointment(); // 失去焦点时触发
            }
        });
        tfAppointmentId.setColumns(10);
        infoPanel.add(tfAppointmentId, gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        infoPanel.add(UIUtil.createLabel("患者姓名："), gbc);
        gbc.gridx = 1;
        taPatientName.setColumns(10);
        infoPanel.add(taPatientName, gbc);

        gbc.gridx = 0;
        gbc.gridy = 2;
        infoPanel.add(UIUtil.createLabel("主诉症状："), gbc);
        gbc.gridx = 1;
        taChiefComplaint.setColumns(10);
        infoPanel.add(taChiefComplaint, gbc);

        gbc.gridx = 0;
        gbc.gridy = 3;
        infoPanel.add(UIUtil.createLabel("现病史："), gbc);
        gbc.gridx = 1;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        infoPanel.add(new JScrollPane(taHistory), gbc);

        gbc.gridx = 0;
        gbc.gridy = 4;
        infoPanel.add(UIUtil.createLabel("初步诊断："), gbc);
        gbc.gridx = 1;
        infoPanel.add(new JScrollPane(taDiagnosis), gbc);

        gbc.gridx = 1;
        gbc.gridy = 5;
        gbc.anchor = GridBagConstraints.EAST;
        JButton btnSave = UIUtil.createButton("保存病历");
        btnSave.addActionListener(e -> saveRecord());
        infoPanel.add(btnSave, gbc);

        // 将所有面板添加到主面板
        add(titlePanel, BorderLayout.NORTH);
        add(infoPanel, BorderLayout.CENTER);
    }

    private void loadAppointment() {
        String input = tfAppointmentId.getText().trim();
        if (input.isEmpty()) return;

        new SwingWorker<Appointment, Void>() {
            @Override
            protected Appointment doInBackground() throws Exception {
                int appointmentId = Integer.parseInt(input);
                return appointmentDao.findById(appointmentId);
            }

            @Override
            protected void done() {
                try {
                    appointment = get();
                    if (appointment != null) {
                        // 更新患者信息
                        taPatientName.setText(patientDao.findById(appointment.getPatientId()).getName());
                        taChiefComplaint.setText(appointment.getChiefComplaint());
                    } else {
                        UIUtil.showError(WriteRecordPanel.this, "未找到对应的会诊记录", "数据错误");
                    }
                } catch (NumberFormatException e) {
                    UIUtil.showError(WriteRecordPanel.this, "请输入有效的数字ID", "输入错误");
                } catch (Exception e) {
                    UIUtil.showError(WriteRecordPanel.this, "数据加载失败：" + e.getMessage(), "系统错误");
                }
            }
        }.execute();
    }

    private void saveRecord() {
        if (appointment == null) {
            UIUtil.showError(this, "请先选择有效的会诊记录", "数据错误");
            return;
        }

        if (taDiagnosis.getText().trim().isEmpty()) {
            UIUtil.showError(this, "诊断结果不能为空", "数据错误");
            return;
        }

        try {
            MedicalRecord record = new MedicalRecord();
            record.setAppointmentId(appointment.getId());
            record.setPatientId(appointment.getPatientId());
            record.setDoctorId(doctor.getId());
            record.setDiagnosis(taDiagnosis.getText());
            record.setAdmissionDate(Date.valueOf(LocalDate.now()));
            record.setPrescription("");
            record.setStatus("新建");

            new MedicalRecordDao().add(record);
            UIUtil.showInfo(this, "病历保存成功", "操作成功");
        } catch (SQLException ex) {
            UIUtil.showError(this, "保存失败：" + ex.getMessage(), "数据库错误");
        }
    }
}